package com.haojiang.mh.remote.ui.frag

import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.TextUtils
import android.view.View
import cn.com.heaton.blelibrary.ble.utils.ByteUtils
import com.haojiang.mh.R
import com.haojiang.mh.remote.base.BaseFrag
import com.haojiang.mh.remote.event.FunChangeEvent
import com.haojiang.mh.remote.utils.BleUtil
import com.haojiang.mh.remote.utils.BleUtil.Companion.lastConnect
import com.haojiang.mh.remote.utils.SpUtil
import com.haojiang.mh.remote.widget.custom.SeekBarColorPicker
import com.haojiang.mh.remote.widget.seekbar.SignSeekBar
import kotlinx.android.synthetic.main.frag_led.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class LedFrag : BaseFrag() {

    private val SECTION_LED_RGB = "section_led_rgb"
    private val SECTION_LED_MIN = "section_led_min"
    private var rgbColor = ""
    private var totalSecs = 5 * 60 //默认5分钟
    private val handler: Handler = object : Handler(Looper.getMainLooper()!!) {
        override fun handleMessage(msg: Message) {

            val bytes = msg.obj as ByteArray
//            LogUtil.e(bytes.toString() + "-----222--")
            BleUtil.dataSend(bytes)
            if (BleUtil.isDevConncted()) {
                lastConnect.bleDeviceList.forEach {
                    SpUtil.putData(context, SECTION_LED_RGB, it.bleAddress, rgbColor)
                }
            }
        }
    }


    private val seekBarColorPickerChangeListener = object : SeekBarColorPicker.SeekBarColorPickerChangeListener {
        override fun onProgressChange(seekBarColorPicker: SeekBarColorPicker?, color: Int, htmlColor: String?) {
            handleColor(htmlColor)
        }

        override fun onSmallCircleClick(htmlRgb: String?) {
            handleColor(htmlRgb)
        }
    }

    private fun handleColor(htmlColor: String?) {
        rgbColor = htmlColor!!
        val b: ByteArray = ByteUtils.hexStr2Bytes(htmlColor)
        val bytes = ByteArray(10)
        bytes[0] = 0x6E
        bytes[1] = 0x0C
        bytes[2] = 0xFF.toByte()
        bytes[3] = b[0]

        for (i in 0..3) {
            bytes[4] = ((bytes[4] + bytes[i]).toByte())
        }

        bytes[5] = 0x6E
        bytes[6] = 0x0D
        bytes[7] = b[1]
        bytes[8] = b[2]
        for (i in 5 until bytes.size - 1) {
            bytes[9] = ((bytes[9] + bytes[i]).toByte())
        }

//        LogUtil.e(ByteUtils.bytes2HexStr(bytes) + "==================")
        val mesage = Message.obtain()
        mesage.obj = bytes
        handler.sendMessageDelayed(mesage, 150)
    }

    private val onProgressChangedListener = object : SignSeekBar.OnProgressChangedListener {
        override fun onProgressChanged(signSeekBar: SignSeekBar?, progress: Int, progressFloat: Float, fromUser: Boolean) {
            totalSecs = progress
            setLedLamp(totalSecs)
        }

        override fun getProgressOnActionUp(signSeekBar: SignSeekBar?, progress: Int, progressFloat: Float) {
            if (BleUtil.isDevConncted()) {
                lastConnect.bleDeviceList.forEach {
                    SpUtil.putData(context, SECTION_LED_MIN, it.bleAddress, progress)
                }
            }
        }

        override fun getProgressOnFinally(signSeekBar: SignSeekBar?, progress: Int, progressFloat: Float, fromUser: Boolean) {

        }
    }

    private fun setLedLamp(seconds: Int) {
        var min = -1
        var sec = -1

//        LogUtil.e(seconds.toString() + "=--=-")

        if (seconds == 0) {
            tvLedMin.visibility = View.VISIBLE
            llLedMin.visibility = View.GONE
//            tvLedSetting.setText(getString(R.string.f_led_keep_on))
//            tvTime.setVisibility(View.GONE)
//            tvUnit.setVisibility(View.GONE)
            return
        } else if (seconds == 1) {
            tvTime.setText(seconds.toString())
            tvUnit.setText(getString(R.string.f_unit_sec))
        } else if (seconds < 60) {
            tvTime.setText(seconds.toString())
            tvUnit.setText(getString(R.string.f_unit_secs))
        } else if (seconds == 60) {
            min = seconds / 60
            tvTime.setText(min.toString())
            tvUnit.setText(getString(R.string.f_unit_min))
        } else if (seconds < 120) {
            min = seconds / 60
            tvTime.setText(min.toString())
            tvUnit.setText(getString(R.string.f_unit_min))
        } else {
            min = seconds / 60
            sec = seconds % 60
            tvTime.setText(min.toString())
            tvUnit.setText(getString(R.string.f_unit_min))
        }

        tvLedSetting.setText(getString(R.string.f_led_setting))
        tvLedMin.visibility = View.GONE
        llLedMin.visibility = View.VISIBLE
//        tvTime.setVisibility(View.VISIBLE)
//        tvUnit.setVisibility(View.VISIBLE)
    }

    override fun onLayoutId(): Int {
        return R.layout.frag_led
    }

    override fun initView() {
        if(!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
//        return View.inflate(context, R.layout.frag_led, null)
    }

    override fun initListener() {
        seekBarColorPicker.setSeekBarColorPickerChangeListener(seekBarColorPickerChangeListener)

        signSeekBar.getConfigBuilder()
            .min(0F) //最小值
            .max(300F) //最大值
            .progress(totalSecs.toFloat())
            .sectionCount(5) //一共5段
//            .thumbColor(ContextCompat.getColor(context!!, R.color.sign_seek_bar_trace)) //
//            .sectionTextColor(ContextCompat.getColor(context!!, R.color.sign_seek_bar_text)) //背景色
            .sectionTextSize(15)
            .setUnit(getString(R.string.f_unit_sec))
            .sectionTextPosition(SignSeekBar.TextPosition.BELOW_SECTION_MARK)
            .build()
        signSeekBar.setOnProgressChangedListener(onProgressChangedListener)
        setLedLamp(totalSecs)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onFunctionEvent(event: FunChangeEvent) {
        lastConnect.surface?.let {
//            if (it.hasLed && !lastConnect.isLedInit) {
            if (it.hasLed) {
//                lastConnect.isLedInit = true
                if (lastConnect.bleDeviceList.size > 0) {
                    rgbColor = SpUtil.getData(
                        context,
                        SECTION_LED_RGB,
                        lastConnect.bleDeviceList[0].bleAddress,
                        ""
                    ) as String
                    if (!TextUtils.isEmpty(rgbColor)) {
                        seekBarColorPicker.setColorByhtmlRGB("#" + rgbColor)
                    }

                    totalSecs = SpUtil.getData(
                        context,
                        SECTION_LED_MIN,
                        lastConnect.bleDeviceList[0].bleAddress,
                        totalSecs
                    ) as Int
                    setLedLamp(totalSecs)
                    signSeekBar.setProgress(totalSecs.toFloat())
                }
            }
        }
//        when (event.fragCode) {
//            CmdUtil.ALARM -> {
//
//            }
//        }
    }

    override fun initDestroy() {
        EventBus.getDefault().unregister(this)
    }
}